#include<stdio.h>
#include<malloc.h>

typedef struct twoStacks TwoStacks;

struct twoStacks{
	int top1, top2, capacity;
	int *arr;
};

TwoStacks *CreateTwoStack(int);
int TSPush1(TwoStacks *, int);
int TSPush2(TwoStacks *, int);
int TSPop1(TwoStacks *);
int TSPop2(TwoStacks *);
int isTS1Empty(TwoStacks *);
int isTS2Empty(TwoStacks *);
int isTSFull(TwoStacks *);

void debug(TwoStacks *);

int main(){
	TwoStacks *ts;
	ts = CreateTwoStack(5);
	int data;
	
	TSPush1(ts, 1);
	debug(ts);
	TSPush2(ts, 5);
	debug(ts);
	TSPush2(ts, 7);
	TSPush2(ts, 8);
	TSPush2(ts, 9);
	debug(ts);
	printf("\nTrying to push 20 to stack1. Result:\t%s", TSPush1(ts, 20)?"True":"False");
	debug(ts);
	printf("\nPopping stuff!\n");
	printf("\nPopping: %s\t%d", (data = TSPop1(ts))?"Got value":"Failed", data);
	debug(ts);
	printf("\nPopping: %s\t%d", (data = TSPop1(ts))?"Got value":"Failed", data);
	debug(ts);
	printf("\nTrying to push 20 to stack1. Result:\t%s", TSPush1(ts, 20)?"True":"False");
	debug(ts);
	printf("\nTrying to push 20 to stack1. Result:\t%s", TSPush1(ts, 20)?"True":"False");
	debug(ts);
		
	printf("\n--Two Stacks using a single array --\n");
	return 0;
}

TwoStacks *CreateTwoStack(int cap){
	TwoStacks *newstack = (TwoStacks *)malloc(sizeof(TwoStacks));
	if(!newstack){
		return NULL;
	}
	newstack->arr = (int *)malloc(sizeof(int) * cap);
	if(!newstack->arr){
		free(newstack);
		return NULL;
	}
	newstack->capacity = cap;
	newstack->top1 = 0;
	newstack->top2 = (cap - 1);
	return newstack;
}

int TSPush1(TwoStacks *TS, int data){
	if(isTSFull(TS)){
		return 0;
	}else{
		TS->arr[TS->top1++] = data;
		return 1;
	}
}

int TSPush2(TwoStacks *TS, int data){
	if(isTSFull(TS)){
		return 0;
	}else{
		TS->arr[TS->top2--] = data;
		return 1;
	}
}

int TSPop1(TwoStacks *TS){
	if(isTS1Empty(TS)){
		return 0;
	}else{
		return TS->arr[--TS->top1];
	}
}

int TSPop2(TwoStacks *TS){
	if(isTS2Empty(TS)){
		return 0;
	}else{
		return TS->arr[++TS->top2];
	}
}

int isTS1Empty(TwoStacks *TS){
	if(TS->top1 == 0){
		return 1;
	}else{
		return 0;
	}
}

int isTS2Empty(TwoStacks *TS){
	if(TS->top2 == (TS->capacity - 1)){
		return 1;
	}else{
		return 0;
	}
}

int isTSFull(TwoStacks *TS){
	return (TS->top1 > TS->top2);
}

void debug(TwoStacks *TS){
	printf("\n--DEBUG--\n");
	printf("\nArray: ");
	int i = 0;
	for(i = 0; i < TS->capacity; i++){
		printf("%d\t", TS->arr[i]);
	}
	printf("\nArrayFull?:\t%s", (isTSFull(TS))?"True":"False");
	printf("\nArrayEmpty?:1.\t%s\t2.\t%s", (isTS1Empty(TS))?"True":"False", (isTS2Empty(TS))?"True":"False");
	printf("\n--DEBUG--\n");
}
